package com.domor.web.controller.system;

import com.domor.common.annotation.Log;
import com.domor.common.core.controller.BaseController;
import com.domor.common.core.domain.AjaxResult;
import com.domor.common.core.page.TableDataInfo;
import com.domor.framework.shiro.service.SysPasswordService;
import com.domor.framework.shiro.util.ShiroUtils;
import com.domor.system.domain.SysUser;
import com.domor.system.service.SysConfigService;
import com.domor.system.service.SysRoleService;
import com.domor.system.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <h3>用户管理控制层</h3>
 * @author liyuyang
 * @date 2020/4/22
 **/
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    private String prefix = "system/user";

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysConfigService configService;

    @GetMapping()
    public String index() {
        return prefix + "/index";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list() {
        Map<String, Object> map = getParameterMap();
        setOrderByAndPage();
        List<SysUser> list = userService.selectUserList(map);
        return getDataTable(list);
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user) {
        String loginName = user.getLoginName();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        if (userService.checkLoginNameUnique(loginName) > 0) {
            return error("新增用户'" + loginName + "'失败，登录账号已存在");
        } else if (userService.checkPhoneUnique(user) > 0) {
            return error("新增用户'" + loginName + "'失败，手机号码已存在");
        } else if (userService.checkEmailUnique(user) > 0) {
            return error("新增用户'" + loginName + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(loginName, password, user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        String[] roleIds = getParameterArray("roleIds");
        return toAjax(userService.insertUser(user, roleIds));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId")Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roleIds", roleService.selectRoleIdsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user) {
        userService.checkUserAllowed(user);
        if (userService.checkPhoneUnique(user) > 0) {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (userService.checkEmailUnique(user) > 0) {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        String[] roleIds = getParameterArray("roleIds");
        return toAjax(userService.updateUser(user, roleIds));
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(Long userId) {
        SysUser ouser = userService.selectUserById(userId);
        userService.checkUserAllowed(ouser);

        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setLoginName(ouser.getLoginName());
        user.setSalt(ShiroUtils.randomSalt());
        String pwd = configService.selectConfigByKey("sys.user.initPassword");
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), pwd, user.getSalt()));

        if (userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getUserId() == user.getUserId()) {
                ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    @RequiresPermissions("system:user:delete")
    @Log(title = "用户管理-删除")
    @PostMapping("/delete/{userId}")
    @ResponseBody
    public AjaxResult delete(@PathVariable("userId") Long userId) {
        try {
            return toAjax(userService.deleteUserById(userId));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @GetMapping("/editPwd")
    public String editPwd(){
        return "index/password";
    }

    @ResponseBody
    @Log(title = "用户管理-修改密码")
    @PostMapping("/editPwd/{userId}")
    public AjaxResult editPwd(@PathVariable("userId") Long userId) {
        try {
            return toAjax(userService.deleteUserById(userId));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

}